﻿using System.Text;

namespace Part2_CancelationToken;

class Program
{
    static async Task Main(string[] args)
    {
        CancellationTokenSource ct = new CancellationTokenSource();
        string path = @"E:\LiufengProjects\RiderProjects\PracticeFile\CancelAtionTokenTest.txt";
        ct.CancelAfter(10000);
        Console.WriteLine(await CancelationTokenTest("https://www.baidu.com",path, ct.Token));
    }

    private static async Task<string> CancelationTokenTest(string path, CancellationToken ct)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 100000; i++)
        {
            ct.ThrowIfCancellationRequested();
            sb.Append($"xxxxxxx+{i}");
        }

        string writeText = sb.ToString();
        byte[] encodingText = Encoding.UTF8.GetBytes(writeText);
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await fs.WriteAsync(encodingText, 0, encodingText.Length, ct);
            }

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    return await sr.ReadToEndAsync(ct);
                }
            }
        }
        catch (OperationCanceledException e)
        {
            {
                Console.WriteLine($"请求被取消:{e.Message}");
                return "";
            }
        }
    }

    private static async Task<string> CancelationTokenTest(string url, string savePath, CancellationToken ct)
    {
        string result = string.Empty;
        try
        {
            for (int i = 0; i < 500; i++)
            {
                using (HttpClient hc = new HttpClient())
                {
                    result = await hc.GetStringAsync(url, ct);
                }
            }
        }
        catch (OperationCanceledException e)
        {
            Console.WriteLine("操作已取消："+e.Message);
            return "";

        }

        return result;
    }
}